package com.info.zhiduoduo.admin.service;

import com.info.zhiduoduo.repository.dto.maker.MakerAlipayPrincipalDto;
import com.info.zhiduoduo.repository.dto.pay.PaymentChild;
import com.info.zhiduoduo.repository.dto.pay.PaymentDetailDto;
import com.info.zhiduoduo.repository.entity.pay.Payment;
import com.info.zhiduoduo.repository.mapper.maker.MakerAlipayPrincipalMapper;
import com.info.zhiduoduo.repository.mapper.pay.PaymentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tianyonghong
 */
@Slf4j
@Service
public class PaymentService {

    @Resource
    private PaymentMapper paymentMapper;

    @Resource
    private MakerAlipayPrincipalMapper makerAlipayPrincipalMapper;

    //获取支付列表
    public List<PaymentChild> getPaymentList(Payment payment) {
        List<Payment> payments = paymentMapper.getPayments(payment.getHidden(), payment.getPayTypeSn(), payment.getSourceTable(), payment.getPayName());

        // 获取所有委托主体列表
        List<MakerAlipayPrincipalDto> principalList = makerAlipayPrincipalMapper.listValid();
        Map<Integer, MakerAlipayPrincipalDto> principalMap = principalList.stream()
        				.collect(Collectors.toMap(MakerAlipayPrincipalDto::getId, a -> a, (k1, k2) -> k1));

        List<PaymentDetailDto> paymentList = new ArrayList();
        for (Payment p : payments){
            PaymentDetailDto dto = new PaymentDetailDto();
            BeanUtils.copyProperties(p,dto);
            paymentList.add(dto);
            if(p.getSourceTable() != 2){
                continue;
            }
            dto.setAlipayPrincipal(principalMap.get(dto.getSourceId()));
        }

        Map<String, List<PaymentDetailDto>> typeMap = paymentList.stream().collect(Collectors.groupingBy(t -> t.getPayTypeSn() + "&" + t.getPayTypeSnName()));

        List<PaymentChild> childList = new ArrayList<>();
        for (String key:typeMap.keySet()) {
            String payTypeSn = key.split("&")[0];
            String payTypeSnName = key.split("&")[1];
            PaymentChild child = new PaymentChild();
            child.setPayTypeSn(payTypeSn);
            child.setPayTypeSnName(payTypeSnName);
            child.setChild(typeMap.get(key));
            childList.add(child);
        }
        return childList;
    }
}
